/**
 * 网络请求
 */
import baseURL from "../static/config/index"

class Http {
  constructor(params) {
    this.baseURL = params.baseURL
  }

  get(url, data) {
    return this.http('GET', url, data)
  }

  post(url, data) {
    return this.http('POST', url, data)
  }

  http(method, url, data) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.baseURL + url,
        data,
        header: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'token': uni.getStorageSync('token')
        },
        method,
        success: ({ data: res }) => {
          if (res.msg === '请先登陆') {
            uni.clearStorageSync()
            uni.reLaunch({ url: '/pages/login/index' })
            return
          }
          if (res.code != 200 && res.msg !== '购物车空空如也' && res.msg !== '查询失败') {
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
          resolve(res)
        },
        fail: (error) => {
          reject(error)
        },
        complete: () => { }
      })
    })
  }
}

const http = new Http({ baseURL })

export default http
